package com.ctsi.offlinesupport.app.rest;

import com.ctsi.commons.util.StringUtil;
import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.IdGen;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.exception.ExceptionFactory;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.mybatis.support.VoTemplate;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.offlinesupport.app.rest.reponse.*;
import com.ctsi.offlinesupport.app.rest.request.AddFlowInfoRequest;
import com.ctsi.offlinesupport.app.rest.request.AgendaTaskQueryRequest;
import com.ctsi.offlinesupport.app.rest.request.SupportQueryRequest;
import com.ctsi.offlinesupport.constant.FlowAction;
import com.ctsi.offlinesupport.constant.FlowStatusConstant;
import com.ctsi.offlinesupport.constant.SupportFlowConstant;
import com.ctsi.offlinesupport.dto.*;
import com.ctsi.offlinesupport.service.*;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.common.model.Person;
import com.ctsi.supportflow.app.entity.*;
import com.ctsi.supportflow.app.vo.ConfirmVO;
import com.ctsi.supportflow.app.vo.IosConfirmVO;
import com.ctsi.supportflow.app.vo.SupportCompleteVO;
import com.ctsi.system.service.api.DictionaryServiceProxy;
import com.ctsi.system.service.api.DictionayTreeServiceProxy;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: zhangjw
 * @Date: 2018/10/9 21:25
 * @Description:
 */
@RestController
public class SupportFlowController {

    @Autowired
    private SupportInfoService supportInfoService;
    @Autowired
    private OfflineSupportService offlineSupportService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private PersonServiceProxy userServiceProxy;
    @Autowired
    private DictionaryServiceProxy dictionaryServiceProxy;
    @Autowired
    private DictionayTreeServiceProxy dictionayTreeServiceProxy;
    @Autowired
    private SupportFlowInfoService supportFlowInfoService;
    @Autowired
    private ExceptionFactory exceptionFactory;
    @Autowired
    private SupportTaskService supportTaskService;
    @Autowired
    private SupportMeetRecordService supportMeetRecordService;
    @Autowired
    private VoTemplate voTemplate;
    @Autowired
    private ProjectEntityService projectEntityService;
    @Autowired
    private CustomEntityService customEntityService;
    @Autowired
    private SupportUtilService supportUtilService;

    @Deprecated
    private SupportInfo toSupportInfo(AddFlowInfoRequest baseSupportInfo) {
        SupportInfo info = baseSupportInfo.toSupportInfo();
        UserInfo user = SecurityUtil.getUser();
        if (info.getSupportType().endsWith(".standard")) {
            info.setStandard(1);
        } else {
            info.setStandard(0);
        }
        //设置人员信息
        String userId = user.getUserId();
        //获取人员信息
        Person userDetials = userServiceProxy.findPersonById(userId);
        info.setApplyUserAdminLevel(userDetials.getAdminLevel()); // 设置发单人行政级别
        info.setApplyUserId(userId);
        // 获取人员得默认部门
        Organise depart = userServiceProxy.getDepart4User(userId);
        info.setApplyUserDepartId(depart.getPartyId());
        // 获取人员默认组织
        Organise organise = userServiceProxy.getOrganise4User(userId);
        info.setApplyUserOrganId(organise.getPartyId());
        //业务单号
        info.setSupportNum(String.valueOf(IdGen.get().nextId()));
        // 设置主键
        info.setId(UUIDGenerator.getId());
        // 设置流程状态
        info.setCurFlowStatus(FlowStatusConstant.NOSTART.value);
        // 设置支撑单提交时间
        info.setSubmitTime(System.currentTimeMillis());
        info.setApplyUserName(userDetials.getFullName());
        info.setDataObjectId(userDetials.getDataObjectId());
        info.setApplyUserDepartChainName(userServiceProxy.getPesonAsc(userId).stream().map(o -> o.getPartyName()).collect(Collectors.joining(">")));
        /**
         * 兼容一期数据,无奈只能冗余一部分数据
         * TODO： 后期有时间了做好信息同步
         */
        ProjectEntity project = projectEntityService.findProjectEntityById(baseSupportInfo.getCustomGroupId());
        info.setProjectName(project.getProjectName());
        CustomEntity custom = customEntityService.findCustomEntityById(baseSupportInfo.getCustomName());
        info.setCustomerName(custom.getCustomName());
        List<String> serviceTypeNames = this.dictionayTreeServiceProxy.getTreeDataNameChain(SupportFlowConstant.SUPPORT_TYPE_TYPE, baseSupportInfo.getSupportType());
        info.setSupportTypeName(StringUtil.join(serviceTypeNames, "/"));
        return info;
    }

    //    @ApiOperation(value = "填报支撑单", notes = "填报支撑单，对象参数JSON格式提交", produces = MediaType.APPLICATION_JSON_UTF8_VALUE
//            , consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParam(name = "addFlowInfoRequest",value = "支撑单内容",paramType = "body",required = true,dataTypeClass = AddFlowInfoRequest.class)
    @PostMapping(value = "/support-flow/infos", consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> submitFlowInfo(@RequestBody AddFlowInfoRequest addFlowInfoRequest) {
        SupportInfo info = this.toSupportInfo(addFlowInfoRequest);
        this.supportInfoService.insertSupportInfo(info);
        return UnifiedResponse.ok();
    }

    //    @ApiOperation(value = "我的发起列表", notes = "当前用户提交或者待提交的支撑单信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
//            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/support-flow/infos/query", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<BaseSupportInfoResponse>> queryPage(@RequestBody SupportQueryRequest query) {
        UserInfo user = SecurityUtil.getUser();

        Map<String, Object> params = UtilHttp.filterBlank(UtilMisc.toMap(query));

        if (query.getBeginTime() != null) {
            params.put("beginTime", query.getBeginTime().getTime());
        }
        if (query.getEndTime() != null) {
            params.put("endTime", query.getEndTime().getTime() + (24 * 3600 * 1000));
        }

        if (UtilValidate.isNotEmpty(query.getCostumGroupId())) {
            params.put("customGroupId", query.getCostumGroupId());
        } else {
            params.put("applyUserId", user.getUserId());
        }

        Page<SupportInfoDTO> infos = this.supportInfoService.findByMulitCondition(params, query.getStart(), query.getPageSize());
        List<SupportInfoDTO> results = infos.getResult();

        List<BaseSupportInfoResponse> responses = results.stream().map(result -> {
            BaseSupportInfoResponse response = this.toBaseSupportInfo(result);
            ApplyUserInfoResponse userInfo = toUserInfoRel(result);
            response.setUserInfo(userInfo);
            String processInstId = result.getProcessInstId();
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstId).active().list();
            String curActiveName = tasks.stream().map(task -> task.getName()).collect(Collectors.joining(","));
            response.setCurActitityName(curActiveName);
//            response.setUserInfo(toUserInfo(result.getApplyUserId(), result.getApplyUserStId(), result.getApplyUserCityId(), result.getApplyUserDepartId(), result.getApplyUserOrganId()));
            return response;
        }).collect(Collectors.toList());
        if (UtilValidate.isNotEmpty(responses)) {
            return UnifiedResponse.ok(new Page(query.getStart(), infos.getTotalCount(), query.getPageSize(), responses));
        }
        return UnifiedResponse.ok(new Page());
    }

    //    @ApiOperation(value = "启动支撑流程", notes = "对支撑信息确认无误后启动支撑流程", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/support-flow/start", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> startFlow(@RequestParam("businessKey") String businessKey) {
        UserInfo user = SecurityUtil.getUser();
        this.offlineSupportService.startSupportFlow(businessKey, user.getUserId(), null,null);
        return UnifiedResponse.ok();
    }

    /**
     * 填报并启动流程
     *
     * @return
     */
//    @ApiOperation(value = "填报支撑单启动支撑流程", notes = "填报并发起支撑流程，对象参数JSON格式提交", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/support-flow/submit-start", consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseStatus(HttpStatus.OK)
    @Deprecated
    public UnifiedResponse<Void> submitAndStart(@RequestBody AddFlowInfoRequest baseSupportInfo) {
        SupportInfo info = toSupportInfo(baseSupportInfo);
        UserInfo user = SecurityUtil.getUser();
        this.offlineSupportService.insertAndstart(info, user.getUserId(), baseSupportInfo.getZcjlId());
        return UnifiedResponse.ok();
    }

    /**
     *
     * @param customGroupId 项目ID
     * @param customName 客户名称
     * @param supportType 支撑类型
     * @param seviceType 服务类型
     * @param requiredFinshtime 请选择完成时间
     * @param projectRequirement 项目需求
     * @param assignedId 任务分配ID
     * @param assignedType 分配类型 role user 两个值
     * @return
     */
    @PostMapping(value = "/support-flow/submit-start")
    public UnifiedResponse<Void> submitAndStart2019(@RequestParam(value = "customGroupId") String customGroupId,
                                                    @RequestParam(value = "customName") String customName,
                                                    @RequestParam(value = "supportType") String supportType,
                                                    @RequestParam(value = "seviceType") String seviceType,
                                                    @RequestParam(value = "requiredFinshtime") String requiredFinshtime,
                                                    @RequestParam(value = "projectRequirement") String projectRequirement,
                                                    @RequestParam(value = "assignedId") String assignedId,
                                                    @RequestParam(value = "assignedType") String assignedType){
        UserInfo user = SecurityUtil.getUser();
        //设置人员信息
        String userId = user.getUserId();
        SupportInfo info = new SupportInfo();
        info.setCustomGroupId(customGroupId);
        info.setCustomName(customName);
        info.setIsAuto(0); // 自动派单废弃，设0
        info.setSupportType(supportType);
        info.setSeviceType(seviceType);
        info.setRequiredFinshtime(UtilDateTime.toLong(requiredFinshtime));
        info.setProjectRequirement(projectRequirement);
        //获取人员信息
        Person userDetials = userServiceProxy.findPersonById(userId);
        info.setApplyUserAdminLevel(userDetials.getAdminLevel()); // 设置发单人行政级别
        info.setApplyUserId(userId);
        // 获取人员得默认部门
        Organise depart = userServiceProxy.getDepart4User(userId);
        info.setApplyUserDepartId(depart.getPartyId());
        // 获取人员默认组织
        Organise organise = userServiceProxy.getOrganise4User(userId);
        info.setApplyUserOrganId(organise.getPartyId());
        //业务单号
        info.setSupportNum(String.valueOf(IdGen.get().nextId()));
        // 设置主键
        info.setId(UUIDGenerator.getId());
        // 设置流程状态
        info.setCurFlowStatus(FlowStatusConstant.NOSTART.value);
        // 设置支撑单提交时间
        info.setSubmitTime(System.currentTimeMillis());
        info.setApplyUserName(userDetials.getFullName());
        info.setDataObjectId(userDetials.getDataObjectId());
        info.setApplyUserDepartChainName(userServiceProxy.getPesonAsc(userId).stream().map(o -> o.getPartyName()).collect(Collectors.joining(">")));
        /**
         * 兼容一期数据,无奈只能冗余一部分数据
         * TODO： 后期有时间了做好信息同步
         */
        ProjectEntity project = projectEntityService.findProjectEntityById(customGroupId);
        info.setProjectName(project.getProjectName());
        CustomEntity custom = customEntityService.findCustomEntityById(customName);
        info.setCustomerName(custom.getCustomName());
        List<String> serviceTypeNames = this.dictionayTreeServiceProxy.getTreeDataNameChain(SupportFlowConstant.SUPPORT_TYPE_TYPE, supportType);
        info.setSupportTypeName(StringUtil.join(serviceTypeNames, "/"));
        Set<String> assignIds = new HashSet<>();
        // 计算流程参与者
        if("role".equalsIgnoreCase(assignedType)){
            if ("flow-zhuren-role".equals(assignedId)) {
                assignIds.add(supportUtilService.findSupportMan(organise.getPartyId()));
            } else {
                assignIds.addAll(supportUtilService.findRoleMember(assignedId));
            }
        } else if ("user".equalsIgnoreCase(assignedType)) {
            assignIds.addAll(Stream.of(assignedId.split(",")).collect(Collectors.toSet()));
        }
        assignedId = assignIds.stream().findAny().get();
        // 计算是否是上报流程
        Organise organ4Assign = userServiceProxy.getOrganise4User(userId);
        if (organ4Assign.getPartyId().equals(organise.getPartyId())) {
            info.setIsReported(0);
        } else {
            info.setIsReported(1);
        }
        // 发起流程
        this.offlineSupportService.insertAndstart2019(info, user.getUserId(), assignedId);
        return UnifiedResponse.ok();
    }


    /**
     * 待办列表 ios 专用
     *
     * @param request
     * @return
     */
//    @ApiOperation(value="待办列表",notes="支撑待办列表",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/support-flow/agenda-tasks")
    @ResponseStatus(HttpStatus.OK)
    @Deprecated
    public UnifiedResponse<Page<AgendaTaskResponse>> agendaTasks(@RequestBody AgendaTaskQueryRequest request) {
        UserInfo user = SecurityUtil.getUser();
        Page<Task> tasks = this.offlineSupportService.agendaTasks(user.getUserId(), request.getStart(), request.getPageSize());
        List<Task> tas = tasks.getResult();
        if (UtilValidate.isNotEmpty(tas)) {
            List<AgendaTaskResponse> responses = tas
                    .stream()
                    .map(ta -> {
                        AgendaTaskResponse agenda = new AgendaTaskResponse();
                        String processInstId = ta.getProcessInstanceId();
                        String buisnessKey = runtimeService.createProcessInstanceQuery().processInstanceId(processInstId).singleResult().getBusinessKey();
                        SupportInfoDTO info = this.supportInfoService.findSupportInfoByProcessInstId(processInstId,user.getUserId());
                        return this.toAgenda(info, ta, user.getUserId());
                    }).collect(Collectors.toList());
            return UnifiedResponse.ok(new Page<AgendaTaskResponse>(request.getStart(), tasks.getTotalCount(), request.getPageSize(), responses));
        }
        return UnifiedResponse.ok(new Page<AgendaTaskResponse>(request.getStart(), tasks.getTotalCount(), request.getPageSize(), Collections.emptyList()));
    }

//    @ApiOperation(value = "待办列表", notes = "支撑待办列表", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/support-flow/todo-tasks")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<BaseSupportInfoResponse>> toDoTaskList(@RequestBody AgendaTaskQueryRequest request) {
        UserInfo user = SecurityUtil.getUser();
        Page<SupportInfoDTO> tasks = this.supportInfoService.queryDaiban(user.getUserId(), request.getStart(), request.getPageSize());
        List<SupportInfoDTO> tas = tasks.getResult();
        if (UtilValidate.isNotEmpty(tas)) {
            List<BaseSupportInfoResponse> responses = tas
                    .stream()
                    .map(ta -> {
                        BaseSupportInfoResponse agenda = new BaseSupportInfoResponse();
                        String processInstId = ta.getProcessInstId();
                        BaseSupportInfoResponse infoResponse = this.toBaseSupportInfo(ta);
                        infoResponse.setCurActivityId(ta.getCurActivityId());
                        infoResponse.setCurActitityName(ta.getCurActivityName());
                        ApplyUserInfoResponse userInfoResponse = toUserInfoRel(ta);
                        infoResponse.setUserInfo(userInfoResponse);
                        infoResponse.setActions(offlineSupportService.getActions(ta.getCurActivityId(), ta.getTaskId(), user.getUserId()));
                        return infoResponse;
                    }).collect(Collectors.toList());
            return UnifiedResponse.ok(new Page<>(request.getStart(), tasks.getTotalCount(), request.getPageSize(), responses));
        }
        return UnifiedResponse.ok(new Page<>(request.getStart(), tasks.getTotalCount(), request.getPageSize(), Collections.emptyList()));
    }

    /**
     * 支撑单详情信息
     *
     * @param taskId
     * @return
     */
    @GetMapping(value = "/support-flow/details/{taskId}")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<SupportDetialsResponse> details(@PathVariable("taskId") String taskId) {
        String userId = SecurityUtil.getUser().getUserId();
        HistoricTaskInstance task = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        SupportInfoDTO info = this.supportInfoService.findSupportInfoByProcessInstId(task.getProcessInstanceId(),userId);
        SupportDetialsResponse details = new SupportDetialsResponse();
        details.setSupportInfo(toBaseSupportInfo(info));
        details.setUserInfo(toUserInfoRel(info));
        // 设置沟通记录
        List<MeetRecordDTO> recordDTOS = supportTaskService.findAllSupportRecords(task.getProcessInstanceId());
        if (UtilValidate.isNotEmpty(recordDTOS)) {
            details.setRecords(recordDTOS);
        }
        //设置专家列表
        List<SupportTask> supportTasks = supportTaskService.findAllAssterTask(task.getProcessInstanceId(), 2);
        List<AssterDTO> adtos = supportTasks.stream().map(st -> {
            return toAssterDTO(st);
        }).collect(Collectors.toList());
        if (adtos != null) {
            details.setAssters(adtos);
        }
        // 设置支撑人员信息列表
        List<SupportTask> supportors = supportTaskService.findAllAssterTask(info.getProcessInstId(), 1);
        List<SupportorInfoResponse> sirs = supportors.stream().map(si -> {
            return toSupportorInfoResponse(si);
        }).collect(Collectors.toList());
        if (UtilValidate.isNotEmpty(sirs)) {
            details.setSupports(sirs);
        }
        // 设置环节ID
        details.setActId(task.getTaskDefinitionKey());
        details.setTaskId(taskId);
        details.setIsProvincial((Integer) taskService.getVariable(taskId, SupportFlowConstant.Variables.ISPROVINCIAL.name));
        details.setIsReported(info.getIsReported());
        details.setActions(offlineSupportService.getActions(task.getTaskDefinitionKey(), taskId, SecurityUtil.getUser().getUserId()));
        return UnifiedResponse.ok(details);
    }

    /**
     * 支撑单详情信息
     *
     * @param businesskey
     * @return
     */
    @GetMapping(value = {"/support-flow/yiban/details/{businesskey}/{taskId}","/support-flow/yiban/details/{businesskey}"})
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<SupportDetialsResponse> yibandetails(@PathVariable("businesskey") String businesskey, @PathVariable(value = "taskId",required = false) String taskId) {
        SupportInfoDTO info = this.supportInfoService.findSupportInfoById(businesskey);
        SupportDetialsResponse details = new SupportDetialsResponse();
        details.setSupportInfo(toBaseSupportInfo(info));
        details.setUserInfo(toUserInfoRel(info));
        if (UtilValidate.isNotEmpty(info.getProcessInstId())) {
            // 设置沟通记录
            List<MeetRecordDTO> recordDTOS = supportTaskService.findAllSupportRecords(info.getProcessInstId());
            if (UtilValidate.isNotEmpty(recordDTOS)) {
                details.setRecords(recordDTOS);
            }
            //设置专家列表
            List<SupportTask> supportTasks = supportTaskService.findAllAssterTask(info.getProcessInstId(), 2);
            List<AssterDTO> adtos = supportTasks.stream().map(st -> {
                return toAssterDTO(st);
            }).collect(Collectors.toList());
            if (adtos != null) {
                details.setAssters(adtos);
            }
            // 设置支撑人员信息列表
            List<SupportTask> supportors = supportTaskService.findAllAssterTask(info.getProcessInstId(), 1);
            List<SupportorInfoResponse> sirs = supportors.stream().map(si -> {
                return toSupportorInfoResponse(si);
            }).collect(Collectors.toList());
            if (UtilValidate.isNotEmpty(sirs)) {
                details.setSupports(sirs);
            }
        } else {
            /**
             * 一期老数据，只设置支撑人员
             */
            List<SupportTask> supportors = supportTaskService.findAllAssterTaskByBk(info.getId(), 1);
            List<SupportorInfoResponse> sirs = supportors.stream().map(si -> {
                return toSupportorInfoResponse(si);
            }).collect(Collectors.toList());
            if (UtilValidate.isNotEmpty(sirs)) {
                details.setSupports(sirs);
            }
        }
        if (UtilValidate.isNotEmpty(taskId)) {
            HistoricTaskInstance task = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
            String actKey = task.getTaskDefinitionKey();
            /**
             * 允许补单的环节
             */
            Set<String> allowFill = new HashSet<>();
            allowFill.add("city-send-activity");
            allowFill.add("provincial-send-activity");
            allowFill.add("depart-role-send-activity");
            if (allowFill.contains(actKey)) {
                details.setTaskId(taskId);
                details.setActId(task.getTaskDefinitionKey());
                String excutionId = offlineSupportService.isCanFill(taskId);
                if (UtilValidate.isNotEmpty(excutionId)) {
                    Set<String> actions = new HashSet<>();
                    actions.add("fill-to-send-supportor");
                    details.setActions(actions);
                }
                details.setExecutionId(excutionId);
            }
        }
        details.setIsReported(info.getIsReported());
        return UnifiedResponse.ok(details);
    }

    private AssterDTO toAssterDTO(SupportTask st) {
        AssterDTO dto = new AssterDTO();
        dto.setMobile(st.getSupportUserPhone());
        dto.setUserId(st.getSupportUserId());
        dto.setUserName(st.getSupportUserName());
        dto.setDepartName(st.getSupportOrganChainName());
        dto.setScore(st.getEvalScore() == null ? "" : st.getEvalScore().toString());
        if (st.getWorkLoad() != null) {
            dto.setWorkLoad(st.getWorkLoad().doubleValue());
        }
        dto.setSupportContent(st.getSupportContent());
        dto.setEvalContent(st.getEvalContent());
        return dto;
    }

    private SupportorInfoResponse toSupportorInfoResponse(SupportTask si) {
        SupportorInfoResponse sir = new SupportorInfoResponse();
        sir.setSupportUserId(si.getSupportUserId());
        sir.setSupportUserName(si.getSupportUserName());
        sir.setSupportUserDepartName(si.getSupportOrganChainName());
        if (si.getWorkLoad() != null) {
            sir.setWorkLoad(si.getWorkLoad().doubleValue());
        }
        sir.setScore(si.getEvalScore() == null ? "" : si.getEvalScore().toString());
        sir.setEvalContent(si.getEvalContent());
        return sir;
    }

    /**
     * 政支主任派单
     *
     * @param taskId
     * @param userId
     * @param comment
     * @return
     */
//    @ApiOperation(value = "政支主任派单", notes = "政支主任派单", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "userId", value = "所派给的人员ID，多个请用逗号拼接"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = false, name = "comment", value = "备注信息")
//    })
    @PostMapping(value = "/support-flow/leader-send-user")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> leaderSend2User(@RequestParam("taskId") String taskId,
                                                 @RequestParam("userId") String userId, @RequestParam(value = "comment", required = false) String comment) {
        String[] userIds = userId.split(",");
        offlineSupportService.leaderSend2User(taskId, SecurityUtil.getUser().getUserId(), userIds, comment);
        return UnifiedResponse.ok();
    }

    /**
     * 地市政支主任上报
     *
     * @return
     */
//    @ApiOperation(value = "地市政支主任上报", notes = "地市政支主任上报", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = false, name = "comment", value = "备注信息")
//    })
    @PostMapping(value = "/support-flow/leader-report-orders")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> report(@RequestParam("taskId") String taskId,
                                        @RequestParam(value = "comment", required = false) String comment) {
        UserInfo user = SecurityUtil.getUser();
        this.offlineSupportService.report(taskId, user.getUserId(), comment);
        return UnifiedResponse.ok();
    }

    /**
     * 部门派单人自动签收，并派单
     *
     * @param taskId
     * @return
     */
//    @ApiOperation(value = "部门派单人派单", notes = "部门派单人派单", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "userIds", value = "所派给的人员ID，多个请用逗号拼接"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = false, name = "comment", value = "备注信息")
//    })
    @PostMapping(value = "/support-flow/depart-send-orders")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> departLeaderSend(@RequestParam("taskId") String taskId,
                                                  @RequestParam("userIds") String userIds, @RequestParam(value = "comment", required = false) String comment) {
        String[] ids = userIds.split(",");
        UserInfo user = SecurityUtil.getUser();
        this.offlineSupportService.claimAndComplete(user.getUserId(), taskId, "supportUserList", comment, ids);
        return UnifiedResponse.ok();
    }

    /**
     * 部门派单人补派
     *
     * @return
     */
//    @ApiOperation(value = "部门派单人补派", notes = "部门派单人补派，该接口可以暂时不对", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "assigns", value = "所派给的人员ID，多个请用逗号拼接")
//    })
    @PostMapping(value = "/support-flow/depart-fill-orders")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> departLeaderFillOrder(@RequestParam("taskId") String taskId,
                                                       @RequestParam("assigns") String assigns,
                                                       @RequestParam(value = "comment",required = false) String comment) {
        String[] ids = assigns.split(",");
        this.offlineSupportService.fill(taskId,comment,SecurityUtil.getUser().getUserId(),ids);
        return UnifiedResponse.ok();
    }

    /**
     * 支撑人员申请协同
     *
     * @param taskId
     * @param userId
     * @return
     */
//    @ApiOperation(value = "支撑人员申请协同", notes = "支撑人员申请协同", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "userId", value = "所派给的人员ID，多个请用逗号拼接")
//    })
    @PostMapping(value = "/support-flow/apply-fill-orders")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> applyFill(@RequestParam("taskId") String taskId, @RequestParam("userId") String userId) {
        this.offlineSupportService.applyFill(taskId, userId);
        return UnifiedResponse.ok();
    }

    /**
     * 支撑人员接单
     *
     * @param taskId
     * @return
     */
//    @ApiOperation(value = "支撑人员接单", notes = "支撑人员接单", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//    })
    @PostMapping(value = "/support-flow/supportor-cliam")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> supportorCliam(@RequestParam("taskId") String taskId) {
        UserInfo user = SecurityUtil.getUser();
        this.offlineSupportService.supportorCliam(taskId, user.getUserId());
        return UnifiedResponse.ok();
    }

//    @ApiOperation(value = "支撑人员办结", notes = "支撑人员办结", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/support-flow/supportor-complete")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> supportorComplete(@RequestBody SupportCompleteVO supportCompleteVO) {
        // 校验是否填写沟通记录
        boolean sub = supportMeetRecordService.isSubmitMeet(supportCompleteVO.getTaskId());
        // 校验是否上传解决方案
        if (sub) {
            offlineSupportService.supportorComplete(supportCompleteVO.getWorkLoad(), supportCompleteVO.getTaskId(), supportCompleteVO.getAdjunctId(), supportCompleteVO.getAssters());
            return UnifiedResponse.ok();
        } else {
            return UnifiedResponse.error("900003", "请先提交沟通记录或支撑内容");
        }
    }

    /**
     * 单独得提交评价接口
     *
     * @param iosconfirmVOS
     * @param taskId
     * @return
     */
    @PostMapping(value = "/support-flow/supportor-eval/{taskId}")
    public UnifiedResponse<Void> supportEval(@RequestBody IosConfirmVO iosconfirmVOS, @PathVariable(value = "taskId") String taskId) {
        offlineSupportService.supportEval(iosconfirmVOS.getConfirmVOS());
        return UnifiedResponse.ok();
    }

    /**
     * 单独得支撑人员办结接口
     *
     * @param workLoad
     * @param taskId
     * @return
     */
    @PostMapping(value = "/support-flow/supportor-sigal-complete")
    public UnifiedResponse<Void> supportSigalComplete(@RequestParam(value = "workLoad") Double workLoad
            , @RequestParam(value = "taskId") String taskId) {
        //Double workLoad, String taskId
        offlineSupportService.supportComplete(workLoad, taskId, null);
        return UnifiedResponse.ok();
    }

//    @ApiOperation(value = "客户经理办结", notes = "客户经理办结", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "path", required = true, name = "taskId", value = "任务ID")
//    })
    @PostMapping(value = "/support-flow/confirm-complete/{taskId}")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> confirmComplete(@RequestBody List<ConfirmVO> confirmVOS, @PathVariable("taskId") String taskId) {
        offlineSupportService.confirmComplete(taskId, confirmVOS);
        return UnifiedResponse.ok();
    }

    @PostMapping(value = "/support-flow/ios-confirm-complete/{taskId}")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> iosConfirmComplete(@RequestBody IosConfirmVO iosconfirmVOS, @PathVariable("taskId") String taskId) {
        offlineSupportService.confirmComplete(taskId, iosconfirmVOS.getConfirmVOS());
        return UnifiedResponse.ok();
    }

    /**
     * 单独的客户经理评价接口
     *
     * @param iosconfirmVOS
     * @return
     */
    @PostMapping(value = "/support-flow/sigal-confirm-eval")
    public UnifiedResponse<Void> sigalConfirmEval(@RequestBody IosConfirmVO iosconfirmVOS) {
        offlineSupportService.confirmEval(iosconfirmVOS.getConfirmVOS());
        return UnifiedResponse.ok();
    }

    /**
     * 单独的客户经理办结接口
     *
     * @param taskId
     * @return
     */
    @PostMapping(value = "/support-flow/sigal-confirm-complete/{taskId}")
    public UnifiedResponse<Void> sigalConfirmComplete(@PathVariable("taskId") String taskId) {
        offlineSupportService.confirmComplete(taskId);
        return UnifiedResponse.ok();
    }

    /**
     * 已办任务
     *
     * @return
     */
//    @ApiOperation(value = "已办任务", notes = "已办任务", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = false, name = "customNameLike", value = "客户名称"),
//            @ApiImplicitParam(dataType = "int", paramType = "form", required = true, name = "start", value = "分页参数"),
//            @ApiImplicitParam(dataType = "int", paramType = "form", required = true, name = "pageSize", value = "分页参数"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = false, name = "status", value = "0，未办结；1已办结")
//    })
    @PostMapping(value = "/support-flow/finished-task", params = "status=0")
    public UnifiedResponse<Page<UserFineshedTaskResponse>> finishedTask(@RequestParam(required = false, value = "customNameLike") String customNameLike,
                                                                        @RequestParam("start") int start,
                                                                        @RequestParam(value = "status") String status,
                                                                        @RequestParam(required = false, value = "customUserName") String customUserName,
                                                                        @RequestParam(required = false, value = "projectName") String projectName,
                                                                        @RequestParam(required = false, value = "seviceType") String seviceType,
                                                                        @RequestParam(required = false, value = "applyUserName") String applyUserName,
                                                                        @RequestParam(required = false, value = "supportUserName") String supportUserName,
                                                                        @RequestParam(required = false, value = "startDate") String startDate,
                                                                        @RequestParam(required = false, value = "endDatee") String endDatee,
                                                                        @RequestParam(required = false, defaultValue = Page.DEFAULT_PAGESIZE, value = "pageSize") int pageSize) {
        UserInfo user = SecurityUtil.getUser();
        Map<String, Object> params = new HashMap<>();
        if (UtilValidate.isNotEmpty(customNameLike)) {
            params.put("customNameLike", "%" + customNameLike + "%");
        }
        if (UtilValidate.isNotEmpty(status) && "1".equalsIgnoreCase(status)) {
            params.put("end", "end");
        } else {
            params.put("noEnd", "noEnd");
        }
        if (UtilValidate.isNotEmpty(customUserName)) {
            params.put("customUserName", "%" + customUserName + "%");
        }
        if (UtilValidate.isNotEmpty(projectName)) {
            params.put("projectName", "%" + projectName + "%");
        }
        if (UtilValidate.isNotEmpty(applyUserName)) {
            params.put("applyUserName", "%" + applyUserName + "%");
        }
        if (UtilValidate.isNotEmpty(supportUserName)) {
            params.put("supportUserName", "%" + supportUserName + "%");
        }
        if (UtilValidate.isNotEmpty(seviceType)) {
            String[] arr = seviceType.split(",");
            params.put("seviceTypes", arr);
        }
        if (UtilValidate.isNotEmpty(startDate)) {
            params.put("startDate", UtilDateTime.toLong(startDate));
        }
        if (UtilValidate.isNotEmpty(endDatee)) {
            params.put("endDatee", UtilDateTime.toLong(endDatee));
        }
        params.put("userId", user.getUserId());
        Page<UserFineshedTaskResponse> page = supportFlowInfoService.userFineshedTask(params, start, pageSize);
        return UnifiedResponse.ok(page);
    }

    /**
     * @param customNameLike
     * @param customGroupIdLike
     * @param beginDate
     * @param endDate
     * @param supportType
     * @param start
     * @param status
     * @param flowStatusId
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/support-flow/finished-task", params = "status=1")
    public UnifiedResponse<Page<BaseSupportInfoResponse>> finishedSupports(@RequestParam(required = false, value = "customNameLike") String customNameLike,
                                                                           @RequestParam(required = false, value = "customGroupIdLike") String customGroupIdLike,
                                                                           @RequestParam(required = false, value = "beginDate") String beginDate,
                                                                           @RequestParam(required = false, value = "endDate") String endDate,
                                                                           @RequestParam(required = false, value = "supportType") String supportType,
                                                                           @RequestParam("start") int start,
                                                                           @RequestParam(required = false, value = "customUserName") String customUserName,
                                                                           @RequestParam(required = false, value = "supportUserName") String supportUserName,
                                                                           @RequestParam(required = false, value = "projectName") String projectName,
                                                                           @RequestParam(required = false, value = "seviceType") String seviceType,
                                                                           @RequestParam(required = false, value = "applyUserName") String applyUserName,
                                                                           @RequestParam(required = false, value = "startDate") String startDate,
                                                                           @RequestParam(required = false, value = "endDatee") String endDatee,
                                                                           @RequestParam(value = "status") String status,
                                                                           @RequestParam(value = "flowStatusId", required = false) String flowStatusId,
                                                                           @RequestParam(required = false, defaultValue = Page.DEFAULT_PAGESIZE, value = "pageSize") int pageSize) {
        UserInfo user = SecurityUtil.getUser();
        Map<String, Object> params = new HashMap<>();
        if (UtilValidate.isNotEmpty(customNameLike)) {
            params.put("customName", "%" + customNameLike + "%");
        }
        if (UtilValidate.isNotEmpty(customGroupIdLike)) {
            params.put("customGroupId", "%" + customGroupIdLike + "%");
        }
        if (UtilValidate.isNotEmpty(customUserName)) {
            params.put("customUserName", "%" + customUserName + "%");
        }
        if (UtilValidate.isNotEmpty(projectName)) {
            params.put("projectName", "%" + projectName + "%");
        }
        if (UtilValidate.isNotEmpty(applyUserName)) {
            params.put("applyUserName", "%" + applyUserName + "%");
        }
        if (UtilValidate.isNotEmpty(supportUserName)) {
            params.put("supportUserName", "%" + supportUserName + "%");
        }
        if (UtilValidate.isNotEmpty(seviceType)) {
            String[] arr = seviceType.split(",");
            params.put("seviceTypes", arr);
        }
        if (UtilValidate.isNotEmpty(startDate)) {
            params.put("startDate", UtilDateTime.toLong(startDate));
        }
        if (UtilValidate.isNotEmpty(endDatee)) {
            params.put("endDatee", UtilDateTime.toLong(endDatee));
        }
        if (UtilValidate.isNotEmpty(beginDate)) {
            long begin = UtilDateTime.toLong(beginDate);
            params.put("flowStartTime", begin);
        }
        if (UtilValidate.isNotEmpty(endDate)) {
            long end = UtilDateTime.toLong(endDate);
            params.put("flowOverTime", end + (24 * 3600 * 1000));
        }
        if (UtilValidate.isEmpty(flowStatusId)) {
            params.put("flowStatusId", FlowStatusConstant.COMPLETE.value);
        } else {
            params.put("flowStatusId", flowStatusId);
        }
        Page<SupportInfoDTO> dtos = supportFlowInfoService.fineshSupportInfo(params, user.getUserId(), user.getLoginId(), start, pageSize);
        List<SupportInfoDTO> tas = dtos.getResult();
        if (UtilValidate.isNotEmpty(tas)) {
            List<BaseSupportInfoResponse> responses = tas
                    .stream()
                    .map(ta -> {
                        BaseSupportInfoResponse infoResponse = this.toBaseSupportInfo(ta);
                        ApplyUserInfoResponse userInfoResponse = toUserInfoRel(ta);
                        infoResponse.setUserInfo(userInfoResponse);
                        return infoResponse;
                    }).collect(Collectors.toList());
            return UnifiedResponse.ok(new Page<>(start, dtos.getTotalCount(), dtos.getPageSize(), responses));
        }
        return UnifiedResponse.ok(new Page<>());
    }

    /**
     * 发起人撤单
     *
     * @param taskId
     * @return
     */
//    @ApiOperation(value = "发起人撤单", notes = "没做要求先不对", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID")
//    })
    @PostMapping(value = "/support-flow/del-process")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> delSupport(@RequestParam("taskId") String taskId) {
        offlineSupportService.delFlow(taskId);
        return UnifiedResponse.ok();
    }

    /**
     * 发起人重启流程
     *
     * @param taskId
     * @return
     */
//    @ApiOperation(value = "发起人重启流程", notes = "没做要求先不对", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = false, name = "comment", value = "备注")
//    })
    @PostMapping(value = "/support-flow/apply-user-send")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Void> restartFlow(@RequestParam("taskId") String taskId, @RequestParam(value = "comment", required = false) String comment) {
        offlineSupportService.applyUserSendSupport(taskId, comment);
        return UnifiedResponse.ok();
    }

    /**
     * 转换用户信息
     *
     * @param supportInfo
     * @return
     */
    private ApplyUserInfoResponse toUserInfoRel(SupportInfoDTO supportInfo) {
        ApplyUserInfoResponse uif = new ApplyUserInfoResponse();
        uif.setUserId(supportInfo.getApplyUserId());
        uif.setMail(supportInfo.getApplyUserMail());
        uif.setPhone(supportInfo.getApplyUserPhone());
        uif.setUserName(supportInfo.getApplyUserName());
        uif.setDepartId(supportInfo.getApplyUserDepartId());
        uif.setOrganId(supportInfo.getApplyUserOrganId());
        String organChainName = supportInfo.getApplyUserDepartChainName();
        if (UtilValidate.isNotEmpty(organChainName)) {
            String[] names = organChainName.split(">");
            if (names.length >= 2) {
                uif.setDepartName(names[names.length-1]);
                uif.setOrganName(names[0]);
            }
        }
        uif.setOrganChainName(supportInfo.getApplyUserDepartChainName());
        return uif;
    }

    /**
     * 转换支撑单基本信息
     *
     * @param result
     * @return
     */
    private BaseSupportInfoResponse toBaseSupportInfo(SupportInfoDTO result) {
        BaseSupportInfoResponse response = new BaseSupportInfoResponse();
        response.setFlowStartTime(UtilDateTime.longToString(result.getFlowStartTime(), "yyyy-MM-dd"));
        response.setTaskId(result.getTaskId());
        if (UtilValidate.isNotEmpty(result.getSeviceType())) {
            response.setServiceType(result.getSeviceType());
            response.setServiceTypeName(this.dictionaryServiceProxy.getDictValue(SupportFlowConstant.SUPPORT_SERVICE_TYPE, result.getSeviceType()));
        }
        if(result.getSubmitTime()!= null){
            response.setSubmitTimeStr(UtilDateTime.longToString(result.getSubmitTime(),"yyyy-MM-dd"));
        }
        response.setSupportType(result.getSupportType());
        if (UtilValidate.isNotEmpty(result.getSupportTypeName())) {
            response.setSupportTypeName(result.getSupportTypeName());
        } else {
            // 期望此处永远不会执行
            List<String> serviceTypeNames = this.dictionayTreeServiceProxy.getTreeDataNameChain(SupportFlowConstant.SUPPORT_TYPE_TYPE, result.getSupportType());
            response.setSupportTypeName(StringUtil.join(serviceTypeNames, "/"));
        }
        response.setProjectRequirement(result.getProjectRequirement());
        response.setProcessInstanceId(result.getProcessInstId());
        response.setSupportNum(result.getSupportNum());
        // 项目客户信息
        response.setCustomGroupId(result.getCustomGroupId());
        response.setCustomName(result.getCustomName());
        response.setBusinessKey(result.getId());
        response.setRequiredFinshtime(UtilDateTime.longToString(result.getRequiredFinshtime(), "yyyy-MM-dd"));
        //response.setIsAutoStr(result.getIsAuto() == 1 ? "自动" : "手动");
        if (result.getIsAuto() == 0) {
            response.setIsSignStr("政支主任派单");
        }else if(result.getIsAuto() == 1) {
            response.setIsSignStr("自动派单");
        }else if (result.getIsAuto() == 2) {
            response.setIsSignStr("指定支撑经理派单");
        }
        response.setIsAunto(result.getIsAuto());
//        response.setIsStandard(result.getStandard());
//        response.setIsStandardStr(result.getStandard() == 1 ? "是" : "否");
        /**
         * 处理项目信息
         */
        if (UtilValidate.isNotEmpty(result.getCustomGroupId())) {
            ProjectEntity project = projectEntityService.findProjectEntityById(result.getCustomGroupId());
            if (project != null) {
                response.setProjectName(project.getProjectName());
                response.setIsSign(project.getIsSign());
                response.setIsSignStr(project.getIsSign() == 0 ? "未签约" : "已签约");
                if (project.getSignDataTime() != null) {
                    response.setSignDateTime(UtilDateTime.longToString(project.getSignDataTime(),"yyyy-MM-dd"));
                }
            }
        } else {
            response.setProjectName(result.getProjectName());
            response.setIsSign(result.getSign());
            response.setIsSignStr(result.getSign() == 0 ? "未签约" : "已签约");
            if (result.getSignDataTime() != null) {
                response.setSignDateTime(UtilDateTime.longToString(result.getSignDataTime(),"yyyy-MM-dd"));
            }
        }
        if (UtilValidate.isNotEmpty(result.getCustomName())) {
            CustomEntity custom = customEntityService.findCustomEntityById(result.getCustomName());
            if (custom != null) {
                response.setCustomNameStr(custom.getCustomName());
            }
        } else {
            response.setCustomNameStr(result.getCustomerName());
        }
        //处理流程信息
        int flowStatusId = result.getCurFlowStatus();
        response.setStatusId(flowStatusId);
        if (flowStatusId == FlowStatusConstant.NOSTART.value) {
            response.setStatusName(FlowStatusConstant.NOSTART.lable);
        } else if (flowStatusId == FlowStatusConstant.STARTED.value) {
            response.setStatusName(FlowStatusConstant.STARTED.lable);
        } else if (flowStatusId == FlowStatusConstant.COMPLETE.value) {
            response.setStatusName(FlowStatusConstant.COMPLETE.lable);
        }
        response.setCurActitityName(result.getCurActivityName());
        response.setCurActivityId(result.getCurActivityId());
        // TODO: 设置是否是回退环节
        response.setIsReported(result.getIsReported());
        if (result.getIsReported() != null) {
            response.setIsReportedStr(result.getIsReported() == 0 ? "否" : "是");
        }
        return response;
    }

    /**
     * 转换待办信息
     *
     * @param info
     * @return
     */
    @Deprecated
    private AgendaTaskResponse toAgenda(SupportInfoDTO info, Task task, String curUserId) {
        AgendaTaskResponse agenda = new AgendaTaskResponse();
        agenda.setActions(offlineSupportService.getActions(task.getTaskDefinitionKey(), task.getId(), curUserId));
        agenda.setCurrentActStatus(info.getCurFlowStatus());
        agenda.setCurrentActId(task.getTaskDefinitionKey());
        agenda.setTaskId(task.getId());
        agenda.setCurrentActName(task.getName());
        agenda.setCustomName(info.getCustomName());
        agenda.setFlowStartTime(UtilDateTime.longToString(info.getFlowStartTime(), "yyyy-MM-dd"));
        agenda.setIsReported(info.getIsReported());
        agenda.setProjectRequirement(info.getProjectRequirement());
        agenda.setRequiredFinshtime(UtilDateTime.longToString(info.getRequiredFinshtime(), "yyyy-MM-dd"));
        agenda.setSupportNum(info.getSupportNum());
        agenda.setSupportId(info.getId());
        agenda.setCustomGroupId(info.getCustomGroupId());
        agenda.setUserInfo(toUserInfoRel(info));
        return agenda;
    }


    /**
     * 流转历史
     * @param businessKey
     * @return
     */
    @GetMapping(value = "/support/process-hits/{businessKey}")
    public UnifiedResponse<List<ProcessHisVO>> processHisRecord(@PathVariable("businessKey") String businessKey) {
        SupportInfoDTO info = this.supportInfoService.findSupportInfoById(businessKey);
        String processInstId = info.getProcessInstId();
        if (UtilValidate.isEmpty(processInstId)) {
            return UnifiedResponse.ok(Collections.emptyList());
        }
        List<ProcessHisDTO> dtos = offlineSupportService.getHisRecord(processInstId);
        if (UtilValidate.isEmpty(dtos)) {
            return UnifiedResponse.ok(Collections.emptyList());
        }
        List<ProcessHisVO> processHisVOS = dtos.stream().map(dto -> {
            ProcessHisVO processHisVO = voTemplate.defaultExcute(new ProcessHisVO(), dto);
            if (FlowAction.BACK.value.equalsIgnoreCase(dto.getActionType())) {
                processHisVO.setActionName(FlowAction.BACK.label);
            } else if (FlowAction.SEND.value.equalsIgnoreCase(dto.getActionType())) {
                processHisVO.setActionName(FlowAction.SEND.label);
            }
            return processHisVO;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(processHisVOS);
    }

//    @ApiOperation(value = "协助部门负责人派单", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "targetUserIds", value = "多人请用逗号隔开"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "comment", value = "备注")
//    })
    @PostMapping(value = "/support-flow/asster-leader-send")
    public UnifiedResponse<Void> assterLeaderSend2User(@RequestParam("taskId") String taskId,
                                                       @RequestParam("targetUserIds") String targetUserIds,
                                                       @RequestParam(required = false, value = "comment") String comment) {
        if (UtilValidate.isEmpty(targetUserIds)) {
            exceptionFactory.throwDefinedException("900002");
        }
        String[] arr = targetUserIds.split(",");
        offlineSupportService.assterLeaderSend2User(taskId, SecurityUtil.getUser().getUserId(), arr, comment);
        return UnifiedResponse.ok();
    }

//    @ApiOperation(value = "专家接单", notes = "专家接单", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID")
//    })
    @PostMapping(value = "/support-flow/asster-accept")
    public UnifiedResponse<Void> assterAccept(@RequestParam("taskId") String taskId) {
        offlineSupportService.assterCliam(taskId, SecurityUtil.getUser().getUserId());
        return UnifiedResponse.ok();
    }


    /**
     * 添加或编辑沟通记录
     *
     * @param taskId
     * @return
     */
//    @ApiOperation(value = "添加或编辑沟通记录", notes = "添加或编辑沟通记录", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(value = "任务ID", name = "taskId", paramType = "path", dataType = "String", required = true),
//            @ApiImplicitParam(value = "yyyy-MM-dd", name = "meetTime", paramType = "path", dataType = "String", required = true),
//            @ApiImplicitParam(value = "项目需求", name = "requirement", paramType = "path", dataType = "String", required = true),
//            @ApiImplicitParam(value = "推进计划", name = "plan", paramType = "path", dataType = "String", required = true)
//    })
    @PostMapping(value = "/support-flow/records/{taskId}")
    public UnifiedResponse<Void> saveOrUpdateRecord(@PathVariable("taskId") String taskId,
                                                    @RequestParam("meetTime") String meetTime, @RequestParam("requirement") String requirement, @RequestParam("plan") String plan) {
        UserInfo user = SecurityUtil.getUser();
        String userId = user.getUserId();
        SupportTask stask = supportTaskService.findSupportTaskByUser(taskId, userId);
        HistoricTaskInstance taskHis = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        String processInstId = taskHis.getProcessInstanceId();
        String bk = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstId).singleResult().getBusinessKey();
        SupportMeetRecord record1 = supportMeetRecordService.findSupportMeetRecordBySupportId(bk);
        if (record1 == null) {
            SupportMeetRecord record = new SupportMeetRecord();
            record.setId(UUIDGenerator.getId());
            record.setSupportId(bk);
            record.setRecordTime(System.currentTimeMillis());
            record.setRequirement(requirement);
            record.setMeetTime(UtilDateTime.toLong(meetTime));
            record.setPlan(plan);
            record.setVersion(0);
            record = supportMeetRecordService.insertSupportMeetRecord(record);
        } else {
            return UnifiedResponse.error("-1", "您已经提交过沟通记录!");
        }
        return UnifiedResponse.ok();
    }


    /**
     * 协助专家完成任务
     *
     * @param taskId
     * @param workLoad
     * @param plan
     * @return
     */
//    @ApiOperation(value = "协助专家完成任务", notes = "协助专家完成任务", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "double", paramType = "form", required = true, name = "workLoad", value = "工作量", example = "2.5"),
//            @ApiImplicitParam(dataType = "String", paramType = "form", required = true, name = "plan", value = "支撑内容")
//    })
    @PostMapping(value = "/support-flow/asster-complete")
    public UnifiedResponse<Void> assterComplete(@RequestParam String taskId,
                                                @RequestParam double workLoad,
                                                @RequestParam String plan) {
        offlineSupportService.assertComplate(SecurityUtil.getUser().getUserId(), taskId, workLoad, plan);
        return UnifiedResponse.ok();
    }


    /**
     * 拉取支撑人员(专家)信息
     *
     * @param taskId
     * @param userRoleType
     * @return
     */
//    @ApiOperation(value = "拉取支撑或专家的任务信息", notes = "支撑人员或专家的支撑信息，在客户经理或者支撑人员确认工作量时拉取信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "path", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "Integer", paramType = "path", required = true, name = "userRoleType", value = "1支撑人员，2协助人员", example = "1")
//    })
    @GetMapping(value = "/support-flow/{userRoleType}/pull-supportinfo/{taskId}")
    public UnifiedResponse<List<SupportResultDTO>> applyUserPullSupportInfo(@PathVariable("taskId") String taskId,
                                                                            @PathVariable("userRoleType") Integer userRoleType) {
        List<SupportResultDTO> result = supportTaskService.findAllSupportTaskDTO(taskId, userRoleType, 2);
        return UnifiedResponse.ok(result);
    }


    /**
     * 拉取支撑人员(专家)信息
     *
     * @param taskId
     * @param userRoleType
     * @return
     */
//    @ApiOperation(value = "拉取支撑或专家的任务信息", notes = "支撑人员或专家的支撑信息，在客户经理或者支撑人员确认工作量时拉取信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(dataType = "String", paramType = "path", required = true, name = "taskId", value = "任务ID，在详情可以获取"),
//            @ApiImplicitParam(dataType = "Integer", paramType = "path", required = true, name = "userRoleType", value = "1支撑人员，2协助人员", example = "1")
//    })
    @PostMapping(value = "/support-flow/{userRoleType}/pull-supportinfo/{taskId}")
    public UnifiedResponse<List<SupportResultDTO>> applyUserPullSupportInfoAndriod(@PathVariable("taskId") String taskId,
                                                                                   @PathVariable("userRoleType") Integer userRoleType) {
        List<SupportResultDTO> result = supportTaskService.findAllSupportTaskDTO(taskId, userRoleType, 2);
        return UnifiedResponse.ok(result);
    }

    @PostMapping(value = "/support-flow/update4")
    public UnifiedResponse<Void> update4(){
        supportTaskService.update4yuejslv();
        return UnifiedResponse.ok();
    }


}
